/*
 * 选择划词后就跳转到 知识助手tab
 * 1. 划词 对整个文档
 * 2. 辅助阅读 对指定的bing
 */
import * as React from 'react';
import {
  Checkbox
} from 'office-ui-fabric-react/lib/Checkbox';
import Toast from '../../components/Toast';
import './styles.less';
import { SearchType } from '../../utils/enum';
import { getTextKeywords } from '../../services/assistant';
import { Toggle } from 'office-ui-fabric-react/lib/Toggle';
import CheckableTag from '../../components/CheckableTag';
import { isSupportWordApi } from '../../utils/WordUtil';


interface SearchFunc {
  (type: SearchType, value: string): void;
}

export interface IFooterProps {
  onSelectedDataChange: SearchFunc
}
export interface IFooterState {
  chapterWrodON?: boolean
  aidReadingON?: boolean
  startLoading?: boolean
  endScaning?: boolean
}

export class Footer extends React.Component<IFooterProps, IFooterState> {
  constructor(props: IFooterProps) {
    super(props);
    this.state = {
      aidReadingON: false
    }
  }

  /* Renders Fabric React checkboxes and wires up the onChange event.*/

  public render() {
    const { aidReadingON, startLoading, endScaning } = this.state
    return (
      <div className="footer-checkbox box-shadow-dark">
        <Toggle
          defaultChecked={false}
          label="划词"
          // onText="On"
          // offText="Off"
          onFocus={() => console.log('onFocus called')}
          onBlur={() => console.log('onBlur called')}
          onChange={this.chapterboxChange}
        />
        {/* <Checkbox
          label='划词'
          onChange={this.chapterboxChange}
          inputProps={{
            onFocus: () => { console.log('Uncontrolled checkbox is focused'); },
            onBlur: () => { console.log('Uncontrolled checkbox is blured'); }
          }} /> */}
        <div className="pull-right">
          <CheckableTag checked={aidReadingON} onChange={this.onChangeAidReading}>
            <span className="icon-container">
              {/* <span onClick={this.deleteContentControl}>
                <embed className="my-svg" src="/assets/eye.svg" width="30" height="20"
                  type="image/svg+xml"
                />
              </span> */}
            </span>
            <div className="read-assist-button hover-card">
              {
                aidReadingON ? (
                  <span className="my-svg">
                    <img src="/assets/eye.svg" alt="" width="20" height="16" />
                  </span>
                ) : (
                    <span className="my-svg" onClick={this.deleteContentControl}>
                      <img src="/assets/off.svg" alt="" width="20" height="16" />
                    </span>
                  )
              }

              辅助阅读
            </div>
          </CheckableTag>
          {/* <Checkbox
            label='辅助阅读'
            // defaultChecked={true}
            onChange={this.readingboxChange} /> */}
        </div>
        {
          startLoading && (
            <div className="read-assist-toast">
              {endScaning ? (
                <div className="toast-content">
                  <span className="loading-icon">
                    <img src="/assets/success.svg" alt="扫描" />
                  </span>
                  <span>辅助阅读已扫描成功</span>
                </div>
              ) : (
                  <div className="toast-content">
                    <span className="loading-icon">
                      <img className="rotate-infinite" src="/assets/loading.svg" alt="load" />
                    </span>
                    <span>辅助阅读开启，扫描中请稍等……</span>
                  </div>
                )}
            </div>
          )
        }
      </div>
    );
  }

  private chapterboxChange = (ev: React.FormEvent<HTMLElement>, isChecked: boolean) => {
    console.log(`开启划词 ${isChecked}.` + ev.timeStamp);
    this.onChangeCapture(isChecked)
  }
  private readingboxChange = (ev: React.FormEvent<HTMLElement>, isChecked: boolean) => {
    console.log(`开启辅助 ${isChecked}.` + ev.timeStamp);
    this.onChangeAidReading(isChecked)
  }



  /**
   * 处理word划词搜索
   */
  onChangeCapture = (isON) => {
    let _toast: Toast = (window as any)._toast

    if (isON) {
      Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, this.onChangeDocument);
      _toast.show('开启划词搜索', 'Completed')
    } else {
      Office.context.document.removeHandlerAsync(Office.EventType.DocumentSelectionChanged, { handler: this.onChangeDocument })
      _toast.show('关闭划词搜索', 'Completed')
    }
  }

  onChangeDocument = eventArgs => {
    eventArgs.document.getSelectedDataAsync(Office.CoercionType.Text,
      { valueFormat: "unformatted", filterType: "all" },
      (asyncResult) => {
        if (asyncResult.status === Office.AsyncResultStatus.Failed) {
          console.log('error')
        } else {
          if (asyncResult.value) {
            this.props.onSelectedDataChange(SearchType.Text, asyncResult.value) //触发
          }
        }
      });
  }


  /**
   * 辅助阅读 需要操作word api 不支持2013 sp1 版本
   * 测试搜索关键词 绑定到word 点击后直接搜索
   *    点击add-in：关键词 绑定到word
   *    点击：移除contentControl
   */

  onChangeAidReading = (isON) => {
    let _toast: Toast = (window as any)._toast
    if (!isSupportWordApi()) {
      return _toast.show('使用Wrod2016以上的版本', 'Info')
    }

    if (isON) {
      Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, this.onReadingAssistChange);
      this.highLightSearchKeyWord()

      this.setState({
        startLoading: true
      })
    } else {
      Office.context.document.removeHandlerAsync(Office.EventType.DocumentSelectionChanged, { handler: this.onReadingAssistChange })
      this.deleteContentControl()
      _toast.show('关闭辅助阅读', 'Completed')
    }
  }

  onReadingAssistChange = eventArgs => {
    const { onSelectedDataChange } = this.props
    Word.run(function (context) {
      const range = context.document.getSelection()
      const contentControl = range.parentContentControl
      context.load(contentControl, 'tag, text');

      return context.sync()
        .then(function () {
          if (contentControl.tag === 'search-keyword') {
            onSelectedDataChange(SearchType.Instance, contentControl.text) //触发
          }
          // console.log('range contentControl', contentControl.text);
        })
        .then(context.sync);
    })
  }
  private deleteContentControl = (e?) => {
    e && e.stopPropagation();
    Word.run(function (context) {
      let contentControls = context.document.contentControls.getByTag('search-keyword');
      context.load(contentControls, 'font, tag');

      return context.sync()
        .then(function () {
          console.info('contentControls with tag has been found in this document', contentControls.items)
          contentControls.items.forEach(
            item => {
              item.font.highlightColor = ""
              item.font.underline = Word.UnderlineType.hidden;
              item.delete(true) // 不删除内容
            }
          )
          console.log('The content control with tag search-keyword has been removed in this document.');
        })
        .then(context.sync);
    })
  }

  private highLightSearchKeyWord = () => { // TODO 通过 后端接口获取高亮的关键词

    const that = this
    // let keyWords = ['共享充电宝', '来电科技', '元璟资本']
    let tempResults = [] // This variable will keep the search results

    Word.run(function (context) {
      var range = context.document.body; // getSelection()
      context.load(range, 'text');

      // Synchronize the document state by executing the queued commands
      // and return a promise to indicate task completion.
      return context.sync()
        .then(async function () {
          const res = await getTextKeywords(range.text)
          const keyWords = res.data
          // todo: 过滤掉包含关系的词条 去长词条
          // const keyWords = filtWords(res.data)
          console.info('高亮', keyWords, range.text)
          if (!keyWords.length) return

          tempResults = keyWords.map(
            (item) => {
              let searchRes = range.search(item, { ignorePunct: true });  // 搜索到的结果 集合
              context.load(searchRes, 'font'); // load 之后才能使用 items属性
              return searchRes
            }
          );
          // console.info('tempResults', tempResults)
        })
        .then(context.sync)
        .then(function () {

          tempResults.forEach(
            (searchResults) => {
              if (searchResults.items && searchResults.items.length) {
                searchResults.items.forEach(
                  item => {
                    // item.font.highlightColor = '#FFFF00'; // Yellow
                    item.font.underline = Word.UnderlineType.double;
                    let contentControl = item.insertContentControl()
                    // contentControl.removeWhenEdited = true;
                    // contentControl.cannotEdit = true;
                    contentControl.tag = 'search-keyword';
                    contentControl.appearance = "Hidden"; // Tags | BoundingBox | Hidden
                  }
                )
              }
            }
          )

        })
        .then(() => {
          that.setState({
            endScaning: true // 结束扫描
          }, () => {
            setTimeout(() => {
              that.setState({
                endScaning: false,
                startLoading: false
              })
            }, 2000)
          })
          return context.sync()
        });
    })
    // .catch(errorHandler);
  }

}
